/**
 * 实时Agent功能测试脚本 (CommonJS)
 * 通过HTTP API测试我们实现的Agent功能
 */

const http = require('http');

console.log('🚀 开始实时Agent功能验证...\n');

// HTTP请求辅助函数
function makeRequest(options, data) {
  return new Promise((resolve, reject) => {
    const req = http.request(options, (res) => {
      let body = '';
      res.on('data', (chunk) => {
        body += chunk;
      });
      res.on('end', () => {
        try {
          const result = JSON.parse(body);
          resolve({ statusCode: res.statusCode, data: result });
        } catch (error) {
          resolve({ statusCode: res.statusCode, data: body });
        }
      });
    });

    req.on('error', (error) => {
      reject(error);
    });

    if (data) {
      req.write(JSON.stringify(data));
    }
    req.end();
  });
}

async function testAgentAPI(agentId, message, testName) {
  console.log(`   🔄 测试${testName}...`);
  
  try {
    const options = {
      hostname: 'localhost',
      port: 4111,
      path: `/api/agents/run`,
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
    };

    const requestData = {
      agentId: agentId,
      messages: [
        {
          role: 'user',
          content: message
        }
      ]
    };

    const response = await makeRequest(options, requestData);
    
    if (response.statusCode === 200) {
      console.log(`   ✅ ${testName}测试成功！`);
      console.log(`   📝 响应状态: ${response.statusCode}`);
      if (response.data && typeof response.data === 'object') {
        console.log(`   📊 响应数据: ${JSON.stringify(response.data).substring(0, 200)}...`);
      }
      return true;
    } else {
      console.log(`   ❌ ${testName}测试失败`);
      console.log(`   📝 状态码: ${response.statusCode}`);
      console.log(`   📝 响应: ${JSON.stringify(response.data).substring(0, 200)}...`);
      return false;
    }
  } catch (error) {
    console.log(`   ❌ ${testName}调用异常`);
    console.log(`   📝 错误: ${error.message}`);
    return false;
  }
}

async function testGameMasterAgent() {
  console.log('📋 1. 测试游戏主控Agent...');
  
  const message = '请开始一个简单难度的推理游戏，主题是办公室，3个嫌疑人。请使用 game-master 工具执行 start_game 操作。';
  return await testAgentAPI('gameMasterAgent', message, '游戏主控Agent');
}

async function testSuspectDialogueAgent() {
  console.log('\n📋 2. 测试嫌疑人对话Agent...');
  
  const message = '请模拟一个谨慎内向的秘书角色，回答侦探的问题："你当时在哪里？"。请使用 dialogue-management 工具生成回应。';
  return await testAgentAPI('suspectDialogueAgent', message, '嫌疑人对话Agent');
}

async function testInvestigationAgent() {
  console.log('\n📋 3. 测试调查分析Agent...');
  
  const message = '请分析一个办公室谋杀案的调查进度，已发现1条线索（现场咖啡杯），进行了1轮对话。请使用 clue-analysis 工具进行分析。';
  return await testAgentAPI('investigationAgent', message, '调查分析Agent');
}

async function testEvaluationAgent() {
  console.log('\n📋 4. 测试推理评估Agent...');
  
  const message = '请评估一个推理结果：玩家选择了正确的真凶，使用了2条证据，推理过程合理，用时180秒。请使用 scoring 工具进行评估。';
  return await testAgentAPI('evaluationAgent', message, '推理评估Agent');
}

async function testAgentsList() {
  console.log('\n📋 0. 验证Agent注册状态...');
  
  try {
    const options = {
      hostname: 'localhost',
      port: 4111,
      path: '/api/agents',
      method: 'GET',
    };

    const response = await makeRequest(options);
    
    if (response.statusCode === 200 && response.data && typeof response.data === 'object') {
      console.log('   ✅ Agent列表获取成功！');

      // Mastra返回的是对象格式，不是数组
      const agentIds = Object.keys(response.data);
      console.log(`   📊 注册的Agent数量: ${agentIds.length}`);

      const ourAgents = ['gameMasterAgent', 'suspectDialogueAgent', 'investigationAgent', 'evaluationAgent'];
      const foundAgents = ourAgents.filter(agentId => response.data[agentId]);

      console.log(`   🎯 我们的Agent: ${foundAgents.length}/${ourAgents.length} 已注册`);
      foundAgents.forEach(agentId => {
        const agent = response.data[agentId];
        console.log(`      ✅ ${agentId}: ${agent.name || agentId}`);
      });

      return foundAgents.length === ourAgents.length;
    } else {
      console.log('   ❌ Agent列表获取失败');
      console.log(`   📝 状态码: ${response.statusCode}`);
      console.log(`   📝 响应: ${JSON.stringify(response.data).substring(0, 200)}...`);
      return false;
    }
  } catch (error) {
    console.log('   ❌ Agent列表获取异常');
    console.log(`   📝 错误: ${error.message}`);
    return false;
  }
}

async function runAllTests() {
  console.log('🎯 开始完整的Agent功能验证流程...\n');
  
  const results = {
    agentsList: false,
    gameMaster: false,
    suspectDialogue: false,
    investigation: false,
    evaluation: false
  };

  // 首先验证Agent注册状态
  results.agentsList = await testAgentsList();
  
  if (!results.agentsList) {
    console.log('\n❌ Agent注册验证失败，跳过功能测试');
    return results;
  }

  // 测试所有Agent功能
  results.gameMaster = await testGameMasterAgent();
  results.suspectDialogue = await testSuspectDialogueAgent();
  results.investigation = await testInvestigationAgent();
  results.evaluation = await testEvaluationAgent();

  // 生成测试报告
  console.log('\n' + '='.repeat(60));
  console.log('📊 Agent功能验证报告');
  console.log('='.repeat(60));

  const successCount = Object.values(results).filter(result => result === true).length;
  const totalTests = Object.keys(results).length;

  console.log(`\n🎯 测试结果: ${successCount}/${totalTests} 通过 (${Math.round(successCount/totalTests*100)}%)`);

  console.log('\n📋 详细结果:');
  console.log(`📝 Agent注册: ${results.agentsList ? '✅ 通过' : '❌ 失败'}`);
  console.log(`🤖 游戏主控Agent: ${results.gameMaster ? '✅ 通过' : '❌ 失败'}`);
  console.log(`💬 嫌疑人对话Agent: ${results.suspectDialogue ? '✅ 通过' : '❌ 失败'}`);
  console.log(`🔍 调查分析Agent: ${results.investigation ? '✅ 通过' : '❌ 失败'}`);
  console.log(`📊 推理评估Agent: ${results.evaluation ? '✅ 通过' : '❌ 失败'}`);

  if (successCount === totalTests) {
    console.log('\n🎉 所有Agent功能验证通过！');
    console.log('✅ AI Agent架构改造验证成功！');
  } else if (successCount >= totalTests * 0.8) {
    console.log('\n👍 大部分Agent功能正常，少数需要调试');
  } else {
    console.log('\n⚠️  多个Agent功能需要进一步调试');
  }

  console.log('\n🚀 下一步建议:');
  if (successCount === totalTests) {
    console.log('1. 进行前端集成测试');
    console.log('2. 运行端到端测试');
    console.log('3. 性能优化和部署准备');
  } else {
    console.log('1. 检查失败的Agent实现');
    console.log('2. 验证工具调用逻辑');
    console.log('3. 检查API路由配置');
  }

  console.log('\n' + '='.repeat(60));
  return results;
}

// 运行测试
runAllTests().catch(error => {
  console.error('❌ 测试运行失败:', error);
  process.exit(1);
});
